package com.ying.controller;

import com.ying.dto.MachineDTO;
import com.ying.dto.PageWrapper;
import com.ying.entity.MachineEntity;
import com.ying.service.MachineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/10/13.
 */
@RestController
@RequestMapping("/machine")
public class MachineController {
    private static final Logger log = LoggerFactory.getLogger(MachineController.class);
    @Autowired
    private MachineService machineService;

    @RequestMapping(value = "/uploadEnergyData", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    public ResponseEntity uploadEnergyData(@RequestParam("machineid") String machineId,
                                           @RequestParam("energy") String energy,
                                           @RequestParam(value = "updatetime") long updatetime,
                                           @RequestParam(value = "username", required = false) String username,
                                           @RequestParam(value = "password", required = false) String password,
                                           @RequestParam(value = "token", required = false) String token,
                                           HttpServletResponse response) {
        log.info("machineId:{},energy:{}", machineId, energy);
        MachineEntity machineEntity = new MachineEntity();
        machineEntity.setMachineId(machineId);
        machineEntity.setUpdatetime(updatetime);
        machineEntity.setEnergy(energy);
        machineService.save(machineEntity);

        return ResponseEntity.ok("result:success\r\n");
    }

    @GetMapping(value = "/energy-list")
    public PageWrapper<MachineDTO> machineEnergyList(Pageable pageable) {
        Page<MachineEntity> page = machineService.findAll(pageable);
        List<MachineDTO> machineDTOS = page.getContent().stream()
                .map(o -> new MachineDTO(o)).collect(Collectors.toList());
        return new PageWrapper<MachineDTO>(page).data(machineDTOS);
    }

}
